home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 19 / CU Amiga Magazine's Super CD-ROM 19 (1998)(EMAP Images)(GB)[!][issue 1998-02].iso / CUCD / Programming / LEDA / source / src / graph_alg / _bellman_ford.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-16  |  1.8 KB  |  75 lines

  1. /*******************************************************************************
  2. +
  3. +  LEDA  3.1c
  4. +
  5. +
  6. +  _bellman_ford.c
  7. +
  8. +
  9. +  Copyright (c) 1994  by  Max-Planck-Institut fuer Informatik
  10. +  Im Stadtwald, 6600 Saarbruecken, FRG     
  11. +  All rights reserved.
  12. *******************************************************************************/
  13.  
  14.  
  15.  
  16. /*******************************************************************************
  17. *                                                                              *
  18. *  BELLMAN FORD                                                                *
  19. *                                                                              *
  20. *******************************************************************************/
  21.  
  22. #include <LEDA/graph_alg.h>
  23. #include <LEDA/b_queue.h>
  24.  
  25.  
  26. bool BELLMAN_FORD(const graph& G, node s, const edge_array<num_type>& cost, 
  27.                                                 node_array<num_type>& dist, 
  28.                                                 node_array<edge>& pred ) 
  29.  
  30. /* single source shortest paths from s using a queue (breadth first search)
  31.    computes for all nodes v:
  32.    a) dist[v] = cost of shortest path from s to v
  33.    b) pred[v] = predecessor edge of v in shortest paths tree
  34. */
  35.  
  36.   node_data<int> count(G,0);
  37.  
  38.   int n = G.number_of_nodes();
  39.  
  40.   node_list Q;
  41.  
  42.   node u,v;
  43.   edge e;
  44.  
  45.   forall_nodes(v,G) 
  46.   { pred[v] = 0;
  47.     dist[v] = max_num; 
  48.    }
  49.  
  50.   dist[s] = 0;
  51.   Q.append(s);
  52.  
  53.   while(! Q.empty() )
  54.   { u = Q.pop();
  55.  
  56.     if (++count[u] > n) return false;   // negative cycle
  57.  
  58.     num_type du = dist[u];
  59.  
  60.     forall_adj_edges(e,u) 
  61.     { v = target(e);
  62.       num_type c = du + cost[e];
  63.       if (c < dist[v]) 
  64.       { dist[v] = c; 
  65.         pred[v] = e;
  66.         if (!Q.member(v)) Q.append(v);
  67.        }
  68.      } 
  69.    }
  70.   return true;
  71. }
  72.  
  73.